package com.yunmai.stepdemo;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.Bundle;

import android.widget.TextView;
import androidx.fragment.app.FragmentActivity;
import com.yunmai.steplibrary.IStepCallBack;
import com.yunmai.steplibrary.IStepCounterBinder;
import com.yunmai.steplibrary.StepCounterBinder;
import com.yunmai.steplibrary.StepService;
import com.yunmai.steplibrary.utils.Log;
import io.reactivex.rxjava3.functions.Consumer;

public class MainActivity extends FragmentActivity implements ServiceConnection {

  private static final String TAG = "MainActivity";
  private Handler handler;
  private IStepCounterBinder mBinder;
  private boolean isBind;
  private TextView textView;


    @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = (TextView)findViewById(R.id.texttv);
      handler = new Handler(getMainLooper());
      permissionGet();
  }

  public void permissionGet(){
    Log.debug("step", "thread：" +android.os.Process.myPid());
    new RxPermissions(this).requestEachCombined(Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.ACCESS_FINE_LOCATION)
        .subscribe(new Consumer<Permission>() {
      @Override public void accept(Permission permission) throws Exception {
        if (permission.granted) {
          handler.postDelayed(new Runnable() {
            @Override public void run() {
              permissionSport();
            }
          },300);
        } else {
          initService();
        }
      }
    });
  }

  public void permissionSport(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
      Log.debug("step", "permissionSport request....");

      new RxPermissions(this).request(Manifest.permission.ACTIVITY_RECOGNITION).subscribe(new Consumer<Boolean>() {
        @Override public void accept(Boolean aBoolean) throws Exception {
          if (aBoolean) {
            initService();
          }
        }
      });
    }else{
      initService();
    }
  }


  public void initService(){
    Intent intent = new Intent(MainActivity.this, StepService.class);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      intent.putExtra("type",1);
      startForegroundService(intent);
    }else{
      intent.putExtra("type",0);
      startService(intent);
    }

    handler.postDelayed(new Runnable() {
      private SensorManager sensorManager;

      @Override public void run() {
        bindService(new Intent(MainActivity.this, StepService.class),
            MainActivity.this, Context.BIND_AUTO_CREATE);



        //sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        ////android4.4以后可以使用计步传感器
        //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        //  Log.debug("step", "tubage:getStepDetector > KITKAT!!! ");
        //  boolean isone =
        //      getPackageManager().hasSystemFeature(PackageManager.FEATURE_SENSOR_STEP_COUNTER);
        //  boolean istwo =
        //      getPackageManager().hasSystemFeature(PackageManager.FEATURE_SENSOR_STEP_DETECTOR);
        //  Log.debug("step", "tubage:initStepSensor!!! ");
        //  Sensor countSensor =
        //      sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);//计步器（一般是开机后，记录历史步数累加值）
        //  Sensor detectorSensor =
        //      sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);//检测器（检测每次步伐数据）
        //  if (isone && countSensor != null) {
        //    Log.debug("step", "tubage:initStepSensor counter ok !!! ");
        //    sensorManager.registerListener(new SensorEventListener() {
        //                                     @Override public void onSensorChanged(SensorEvent sensorEvent) {
        //
        //                                     }
        //
        //                                     @Override public void onAccuracyChanged(Sensor sensor, int i) {
        //
        //                                     }
        //                                   }, countSensor,
        //        SensorManager.SENSOR_DELAY_NORMAL);
        //  } else if (istwo && detectorSensor != null) {
        //    Log.debug("step", "tubage:initStepSensor detector ok!!! ");
        //    sensorManager.registerListener(new SensorEventListener() {
        //                                     @Override public void onSensorChanged(SensorEvent sensorEvent) {
        //
        //                                     }
        //
        //                                     @Override public void onAccuracyChanged(Sensor sensor, int i) {
        //
        //                                     }
        //                                   }, detectorSensor,
        //        SensorManager.SENSOR_DELAY_NORMAL);
        //  }else{
        //    Log.debug("step", "tubage:no support step CounterSensor!!! ");
        //  }
        //}
      }
    },300);
    Log.debug("step", "initService  ready");
  }
  @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
    isBind = true;
    mBinder = StepCounterBinder.Stub.asInterface(iBinder);
    try {
      mBinder.registerCallBack(new IStepCallBack.Stub() {
        @Override public void callBack(int allCount, int currentCount) throws RemoteException {
          handler.post(new Runnable() {
            @Override public void run() {
              Log.debug("step","tubage:step callBack ....."+allCount+" currentcount:"+currentCount);
              if(allCount>0 && currentCount == 0){
                textView.setText("当前zong 步数 "+ allCount);
              }else{
                textView.setText("当前步数 ："+currentCount);
              }
            }
          });
        }
      });
    } catch (RemoteException e) {
      e.printStackTrace();
    }
    Log.debug("step","tubage:onServiceConnected .....");
  }

  @Override public void onServiceDisconnected(ComponentName componentName) {
    Log.debug("step","tuabge:onServiceDisconnected .....");
    isBind = false;
    mBinder = null;
  }

  @Override protected void onDestroy() {
    super.onDestroy();
    if(isBind){
      unbindService(MainActivity.this);
    }
  }
}